--
-- Description: Script to save an event type.
-- This includes inserting a new record in the EventTypes table
-- if the EventTypeName does not exist.
-- Returns the EventTypeID.
-- Date created: 2 May 2008
--

set ANSI_NULLS on
set QUOTED_IDENTIFIER on
go

--
-- drop the procedure if it exists and recreate it.
--
if exists
(
	select * 
	from sys.objects
	where object_id = object_id(N'[dbo].[saveEventType_sp]')
	and type in (N'P', N'PC')
)

begin
    drop procedure [dbo].[saveEventType_sp]
end
go

create procedure [dbo].[saveEventType_sp]
(
    @EventTypeName nvarchar(50)
)
as
begin
	--
	-- validate the @EventTypeName. It cannot be null or empty.
	--
	if (@EventTypeName is null or LEN(@EventTypeName) = 0)
	begin
		raiserror
		(
			N'@EventTypeName parameter cannot be null or empty.'
			, 10 -- severity
			, 1 -- state
		)
	end
	
	declare @EventTypeID int

	--
	-- check if the event type name exists in the table.
	--
	if not exists
	(
		select top 1 1
		from [dbo].[EventTypes]
		where EventTypeName = @EventTypeName
	)
	begin
		--
		-- create a new record with the new event type name.
		--
		insert into [dbo].[EventTypes]
		(
			EventTypeName
		)
		values
		(
			@EventTypeName
		)
	end

	--
	-- get the event type id for the event type name.
	--
	select @EventTypeID = EventTypeID
	from [dbo].[EventTypes]
	where EventTypeName = @EventTypeName

	--
	-- return the result.
	--
	return @EventTypeID
end
go

set ansi_nulls off
go
set quoted_identifier off
go
